<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业实现低成本数字化转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\energy;

use think\App;
use app\controller\property\Base;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\energy\EnergySharedLogsRepository;
use app\common\repositories\energy\EnergySharedPlanRepository;
use app\common\repositories\energy\EnergySharedRoomRepository;

class EnergySharedRoom extends Base
{
    protected $repository;

    public function __construct(App $app, EnergySharedRoomRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    /**
     * 公摊方案列表
     * @return string|\think\response\Json
     * @throws \Exception
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'plan_id' => '',
                'keywords' => ''
            ]);
            $where['is_settle'] = 1;
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('energy/shared/room/list', [
            'addAuth' => property_auth('propertyEnergySharedPlanAdd'),
            'editAuth' => property_auth('propertyEnergySharedPlanEdit'),
            'delAuth' => property_auth('propertyEnergySharedPlanDel'),
            'detailAuth' => property_auth('propertyEnergySharedPlanDetail'),
        ]);
    }

    /**
     * 添加公摊房间
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     */
    public function add()
    {
        $planId = (int)$this->request->param('plan_id');
        /** @var EnergySharedPlanRepository $energySharedPlanRepository */
        $energySharedPlanRepository = app()->make(EnergySharedPlanRepository::class);
        $sharedPlanInfo = $energySharedPlanRepository->get($planId);
        if ($this->request->isAjax() && $this->request->isGet()) {
            $where = $this->request->param([
                'unit_id' => '',
                'room_floor' => '',
                'room_id' => '',
            ]);
            $where['property_id'] = $sharedPlanInfo['property_id'];
            $roomIds = $this->repository->getSearch([])
                ->where('plan_id', $planId)
                ->where('property_id', $sharedPlanInfo['property_id'])
                ->column('room_id');
            /** @var RoomBasicRepository $roomBasicRepository */
            $roomBasicRepository = app()->make(RoomBasicRepository::class);
            $res = $roomBasicRepository->search($where, $this->request->propertyId)
                ->where('id', 'not in', $roomIds)
                ->append(['full_room_name'])
                ->visible(['full_room_name', 'id'])
                ->select()->toArray();
            return json()->data(['code' => 0, 'data' => $res]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'plan_id' => '',
                'room' => [],
            ]);
            foreach ($param['room'] as $k => $v) {
                if (!isset($param['room'])) {
                    unset($param['room'][$k]);
                }
            }
            $param['room'] = array_filter($param['room']);
            try {
                $res = $this->repository->schemeConfig($sharedPlanInfo, $param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('录入公摊房间失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('energy/shared/room/add', [
                'planId' => $planId,
                'sharedPlanInfo' => $sharedPlanInfo
            ]);
        }
    }

    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'scale' => '',
                'remark' => '',
                'use_num_z' => '',
            ]);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('均摊信息修改失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('energy/shared/room/edit', [
                'info' => $info,
            ]);
        }
    }

    public function detail()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'shared_room_id' => '',
                'keywords' => '',
                'add_time' => '',
            ]);
            [$page, $limit] = $this->getPage();
            /** @var EnergySharedLogsRepository $energySharedLogsRepository */
            $energySharedLogsRepository = app()->make(EnergySharedLogsRepository::class);
            $res = $energySharedLogsRepository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('energy/shared/room/detail');
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('公摊明细删除失败', $e);
            return $this->error('网络失败');
        }
    }

}